<template>
  <div id="addList">
    <TopBar title="地址列表" />
    <div class="addlist">
      <van-address-list
      v-model="chosenAddressId"
      :list="list"
      default-tag-text="默认"
      @add="onAdd"
      @edit="onEdit"
    />
    </div>
  </div>
</template>

<script>
import { Toast } from 'vant';
import {TopBar} from '@/components/'

export default {
  components: {
    TopBar
  },
  data() {
    return {
      chosenAddressId: '',
      list: [],
    };
  },
  watch: {
    chosenAddressId() {
      const params = {
        _id: this.chosenAddressId
      }
      this.$api.userupdateaddr(params).then(res => {
        console.log(res);
        this.init();
      })
    }
  },
  mounted() {
    this.init()
  },
  methods: {
    init(){
      this.list.length = 0;
      this.$api.userAddr().then(res => {
        if(!res) return Toast('地址列表为空')
        res.map(item =>{
          let obj = {
          id: item._id,
          name: item.username,
          tel: item.phone,
          address: item.addr,
          isDefault: item.primary
        }
        this.list.push(obj)
        if(item.primary) this.chosenAddressId = item._id
        })
        console.log('list: '+this.list);
      })
    },
    onAdd() {
      Toast('新增地址');
      this.$router.push('/addaddr')
    },
    onEdit(item, index) {
      Toast('编辑地址:' + index);
    },
  },
};
</script>

<style>
.addlist h1 {
  text-align: center;
  font-size: 2.6rem;
  margin-top: 10rem;
}
</style>